import axios from "axios";
import {
  BASE_URL
} from "./tools";
import {
  getToken
} from "./auth";
import {
  Notify
} from "vant"; // 引入消息提示

const instance = axios.create({
  baseURL: BASE_URL, // BASE_URL = "http://localhost:3009"
  timeout: 5000,
});

// 请求拦截 (可以把统一的请求头儿放里面)
instance.interceptors.request.use(
  function (config) {
    if (getToken()) {
      //表示统一设置请求头
      config.headers.authorization = "Bearer " + getToken();
    }
    return config;
  },
  function (error) {
    return Promise.reject(error);
  }
);

// 响应拦截
instance.interceptors.response.use(
  function (response) {
    return response.data;
  },
  function (error) {
    const {
      status
    } = error.response;
    if (status === 401) {
      Notify({
        type: "warning",
        message: "未授权，请先登录"
      });
      // 跳转到登陆页面,提示一下未授权
      window.location.href = "#/zanghao";
    }
    return Promise.reject(error);
  }
);
// 封装get请求
export const get = (url, params) => instance.get(url, {
  params: params
});
// 封装post请求
export const post = (url, data) => instance.post(url, data); // 服务端通过req.body获取post或者put的请求参数
// 封装delete请求
export const del = (url, params) => instance.delete(url, {
  params
}); // ?req.query
export default instance;

/*
axios.get('/user', {
params: {
    ID: 12345
}
})
axios.post('/user', {
    firstName: 'Fred',
    lastName: 'Flintstone'
  })
*/